<template>
    <div class="blank-box" v-if="props.topicList">
        <div class="paragraph">
            <!-- <div
                ref="htmlContainer"
                v-for="(list, index) in renderedHtml"
                class="paragraph-list"
                :key="index">
                <label class="num-text">
                    {{ list.orderNum }}
                </label>
                <span class="html-content" v-html="list.html"></span>
            </div> -->
            <div class="paragraph-list" ref="htmlContainer" v-for="(item, index) in formatTopic" :key="index">
                <label class="num-text">
                    {{ item.orderNum }}
                </label>
                <!-- // 输入题没有内容只有输入框的情况 -->
                <template v-if="item.topicName === null">
                    <div class="html-content" v-if="showAnswer">
                        <span v-if="item.isRight === 1" class="span-answer">{{item.userAnswer}}</span>
                        <span v-else>
                            <label class="error-answer">{{item.userAnswer || '未作答'}}</label>
                            <label style="color: #0590ff;">({{formatAnswer(item.rightAnswer)}})</label>
                        </span>
                        <template v-if="item.haveAnalysis || item.haveLocation">
                            <topic-analysis
                                :btn="{position: item.haveLocation, analysis: item.haveAnalysis}"
                                :part-id="partId"
                                :topic-id="item.topicId"
                                :exam-id="examId"
                                :topic-type="topicType"
                                @to-position="(val) => emit('to-position', val)"
                                @popup-show="(val) => emit('popup-show', val)"
                            />
                        </template>
                    </div>
                    <div class="html-content" v-else>
                        <span class="input-span">
                            <input class="input-single" :class="[props.keyClass]" type="text" maxlength="60" :data-topic="item.topicId" :value="item.userAnswer || ''">
                        </span>
                    </div>
                </template>
                <!-- // 输入题有内容 并且 输入框是 根据 @# 替换的情况 -->
                <template v-else-if="item.topicName.indexOf('@#') !== -1">
                    <div class="html-content" v-if="showAnswer">
                        <span v-html="formatAnswerInput(item)"></span>
                        <template v-if="item.haveAnalysis || item.haveLocation">
                            <topic-analysis
                                :btn="{position: item.haveLocation, analysis: item.haveAnalysis}"
                                :part-id="partId"
                                :topic-id="item.topicId"
                                :exam-id="examId"
                                :topic-type="topicType"
                                @to-position="(val) => emit('to-position', val)"
                                @popup-show="(val) => emit('popup-show', val)"
                            />
                        </template>
                    </div>
                    <div class="html-content" v-else>
                        <span v-html="formatInput(item)"></span>
                    </div>
                </template>
                <!-- // 只有在文本最后有一个输入框 且 没有 @# 字符的情况 -->
                <template v-else>
                    <div class="html-content" v-if="showAnswer">
                        <span class="span-answer" v-if="item.isRight === 1">
                            <span v-html="item.topicName"></span>
                            <span class="span-answer">{{item.userAnswer}}</span>
                        </span>
                        <span v-else>
                            <span v-html="item.topicName"></span>
                            <span>
                                <label
                                    style="
                                        font-size: 0.933rem;
                                        border-bottom: 1px solid #000;
                                        min-width: 70px;
                                        height: 23px;
                                        display: inline-block;
                                        text-align: center;
                                        margin: 0 5px;
                                        color: #FD453D;"
                                >
                                    {{item.userAnswer || '未作答'}}
                                </label>
                                <label style=" color: #0590ff;font-size: 0.933rem;">({{formatAnswer(item.rightAnswer)}})</label>
                            </span>
                        </span>
                        <template v-if="item.haveAnalysis || item.haveLocation">
                            <topic-analysis
                                :btn="{position: item.haveLocation, analysis: item.haveAnalysis}"
                                :part-id="partId"
                                :topic-type="topicType"
                                :exam-id="examId"
                                :topic-id="item.topicId"
                                @to-position="(val) => emit('to-position', val)"
                                @popup-show="(val) => emit('popup-show', val)"
                            />
                        </template>
                    </div>
                    <div class="html-content" v-else>
                        <span v-html="item.topicName"></span>
                        <span class="input-span">
                            <input
                                class="input-single"
                                :class="[props.keyClass]"
                                maxlength="60"
                                :data-topic="item.topicId"
                                :value="item.userAnswer || ''"
                            >
                        </span>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, nextTick, onMounted, ref } from 'vue'
import topicAnalysis from './topicAnalysis.vue'

const props = defineProps(['topicList', 'showAnswer', 'keyClass', 'partId', 'topicType', 'examId'])
const emit = defineEmits(['inputBlue', 'inputFocus', 'to-position', 'popup-show'])
const formatTopic = computed(() => {
    return props.topicList.map(item => {
        let userAnswerList = []
        if (item.userAnswer) {
            userAnswerList = item.userAnswer.split('#')
        }
        return {
            ...item,
            userAnswerList
        }
    })
})

function hasMore(name = '') {
    return (name.match(/@#/g) || []).length
}

// 渲染显示答案时的答题框和正确答案
function formatAnswerInput(item) {
    let html = item.topicName
    const more = hasMore(item.topicName)
    if (more > 1) {
        // 一个题有多个空时取有答案的题目列表
        const filterTopicList = item.subTopicList.filter(item => item.rightAnswer)
        filterTopicList.forEach((sub, i) => {
            const last = i + 1 == filterTopicList.length
            html = html.replace('@#', () => {
                if (item.isRight === 1) {
                    return `<span class="span-answer">${sub.userAnswer}</span>`
                } else {
                    // 需求：在一行里有多个输入框时 正确答案只在最后一个输入框后显示答案。
                    return `<span>
                                <label class="error-answer">${sub.userAnswer || '未作答'}</label>
                                <label style=" color: #0590ff;display:${last ? 'inherit' : 'none'}">(${formatAnswer(item.rightAnswer)})</label>
                            </span>`
                }
            })
        })
    } else {
        if (item.isRight === 1) {
            return `<span class="span-answer">${item.userAnswer}</span>`
        }
        return `<span>
                    <label class="error-answer">${item.userAnswer || '未作答'}</label>
                    <label style=" color: #0590ff;">(${formatAnswer(item.rightAnswer)})</label>
                </span>`
    }
    return html
}

// 渲染答题时的输入框
function formatInput(item) {
    let html = item.topicName
    const more = hasMore(item.topicName)
    if (more > 1) { // 一个题有多个输入框的情况
        // 一个题有多个空时取有答案的题目列表
        const filterTopicList = item.subTopicList.filter(item => item.rightAnswer)
        filterTopicList.forEach(sub => {
            // 把@#替换成输入框
            html = html.replace('@#', () => {
                return `<span class="input-span">
                            <input 
                                maxlength="60" 
                                data-type="2" 
                                data-topic="${item.topicId}" 
                                value="${sub.userAnswer || ''}"
                                class="input-single ${props.keyClass} blank-${item.topicId}"
                            />
                        </span>`
            })
        })
    } else {
        html = item.topicName.replace('@#', () => {
            return `<span class="input-span">
                        <input 
                            type="text" 
                            maxlength="60" 
                            data-topic="${item.topicId}" 
                            value="${item.userAnswer || ''}"
                            class="input-single ${props.keyClass}"
                        />
                    </span>`
        })
    }
    return html
}

const renderedHtml = computed(() => {
    const dataList = []
    props.topicList.forEach((item) => {
        let subHtml = ''
        // 输入题没有内容只有输入框的情况
        if (item.topicName === null) {
            if (props.showAnswer) {
                if (item.isRight === 1) {
                    subHtml = `<span class="span-answer">${item.userAnswer}</span>`
                } else {
                    subHtml = `<span>
                            <label class="error-answer">${
    item.userAnswer ? item.userAnswer : '未作答'
}</label>
                            <label style=" color: #0590ff;">(${item.rightAnswer})</label>
                        </span>`
                }
            } else {
                subHtml = `<span class="input-span"><input maxlength="60" data-topic="${
                    item.topicId
                }" value="${item.userAnswer ? item.userAnswer : ''}" class="input-single ${
                    props.keyClass
                }" /></span>`
            }
        } else if (item.topicName.indexOf('@#') !== -1) {
            // 输入题有内容 并且 输入框是 根据 @# 替换的情况
            if (props.showAnswer) {
                const count = (item.topicName.match(/@#/g) || []).length
                if (count > 1) {
                    subHtml = item.topicName
                    let userAnswerList = ['', '']
                    if (item.userAnswer) {
                        userAnswerList = item.userAnswer.split('#')
                    }
                    item.subTopicList.forEach((subItem, subIndex) => {
                        // 内容中最后一个不需要输入框
                        if (subIndex + 1 < item.subTopicList.length) {
                            subHtml = subHtml.replace('@#', () => {
                                let routeHtml = ''
                                if (item.isRight === 1) {
                                    routeHtml = `<span class="span-answer">${userAnswerList[subIndex]}</span>`
                                } else {
                                    // 需求：在一行里有多个输入框时 正确答案只在最后一个输入框后显示答案。
                                    if (subIndex + 2 == item.subTopicList.length) {
                                        routeHtml = `<span style="">
                            <label class="error-answer">${
    userAnswerList[subIndex] ? userAnswerList[subIndex] : '未作答'
}</label>
                            <label style=" color: #0590ff;">(${item.rightAnswer})</label>
                        </span>`
                                    } else {
                                        routeHtml = `<span style="">
                            <label class="error-answer">${
    userAnswerList[subIndex] ? userAnswerList[subIndex] : '未作答'
}</label>
                        </span>`
                                    }
                                }
                                return routeHtml
                            })
                        }
                    })
                } else {
                    subHtml = item.topicName.replace(/@#/g, () => {
                        let routeHtml = ''
                        if (item.isRight === 1) {
                            routeHtml = `<span class="span-answer">${item.userAnswer}</span>`
                        } else {
                            routeHtml = `<span style="">
                            <label class="error-answer">${
    item.userAnswer ? item.userAnswer : '未作答'
}</label>
                            <label style=" color: #0590ff;">(${item.rightAnswer})</label>
                        </span>`
                        }
                        return routeHtml
                    })
                }
            } else {
                const count = (item.topicName.match(/@#/g) || []).length
                if (count > 1) {
                    subHtml = item.topicName
                    item.subTopicList.forEach((subItem, subIndex) => {
                        // 内容中最后一个不需要输入框
                        if (subIndex + 1 < item.subTopicList.length) {
                            subHtml = subHtml.replace('@#', () => {
                                return `<span class="input-span"><input maxlength="60" data-type="2" data-topic="${
                                    item.topicId
                                }" value="${
                                    subItem.userAnswer ? subItem.userAnswer : ''
                                }" class="input-single ${props.keyClass} blank-${
                                    item.topicId
                                }"  /></span>`
                            })
                        }
                    })
                } else {
                    subHtml = item.topicName.replace(/@#/g, () => {
                        return `<span class="input-span"><input maxlength="60" data-topic="${
                            item.topicId
                        }" value="${item.userAnswer ? item.userAnswer : ''}" class="input-single ${
                            props.keyClass
                        }"  /></span>`
                    })
                }
            }
        } else {
            // 只有在文本最后有一个输入框 且 没有 @# 字符的情况
            if (props.showAnswer) {
                if (item.isRight === 1) {
                    subHtml = item.topicName + `<span class="span-answer">${item.userAnswer}</span>`
                } else {
                    subHtml =
                        item.topicName +
                        `<span style="">
                            <label style="font-size: 0.933rem; border-bottom: 1px solid #000; min-width: 70px;  height: 23px;display: inline-block;text-align: center; margin: 0 5px; color: #FD453D;">${
    item.userAnswer ? item.userAnswer : '未作答'
}</label>
                            <label style=" color: #0590ff;font-size: 0.933rem;">(${
    item.rightAnswer
})</label>
                        </span>`
                }
            } else {
                subHtml =
                    item.topicName +
                    `<span class="input-span"><input maxlength="60" data-topic="${
                        item.topicId
                    }" value="${item.userAnswer ? item.userAnswer : ''}" class="input-single ${
                        props.keyClass
                    }"  /></span>`
            }
        }
        item.html = subHtml
        dataList.push(item)
    })
    return dataList
})

const htmlContainer = ref(null)
onMounted(() => {
    bindHandle()
})

// 绑定事件
async function bindHandle() {
    await nextTick(() => {
        // keyClass 用来防止事件绑定多次的问题。
        // 为每个 <input> 元素添加事件监听器 input-single
        document.querySelectorAll('input.' + props.keyClass).forEach((input, index) => {
            input.removeEventListener('blur', inputBlur)
            input.removeEventListener('focus', inputFocus)
            input.addEventListener('blur', (event) => inputBlur(event, index, event.target.value))
            input.addEventListener('focus', (event) => inputFocus(index, event.target.value))
        })
    })
}

// 输入框失去焦点
function inputBlur(event, index, value) {
    console.log('类型：', event.target.dataset.type)
    if (event.target.dataset.type) {
        // 一行多个空格的情况
        const inputs = document.querySelectorAll('.blank-' + event.target.dataset.topic)
        const values = []
        for (let i = 0; i < inputs.length; i++) {
            values.push(inputs[i].value)
        }
        value = values.join('#')
    }
    const paramAnswer = {
        topicId: parseInt(event.target.dataset.topic), // props.topicList[index].topicId,
        userAnswer: value.trim()
    }
    emit('inputBlue', paramAnswer)
}

// 获取焦点
function inputFocus(index, value) {
    emit('inputFocus', value)
}

function formatAnswer(answer) {
    return answer.replaceAll('@', '/').replaceAll('#', '，')
}
</script>

<style scoped lang="scss">
.blank-box {
    .paragraph {
        .paragraph-list {
            line-height: 30px;
            font-size: 16px;
            display: flex;
            justify-content: flex-start;
        }
    }
    .html-content {
        ::v-deep .input-single {
            background-color: transparent;
            max-width: 70px;
            border-radius: 0;
            padding: 0;
            border: none;
            color: #000;
            outline: none;
            display: inline-block;
            text-align: center;
            position: absolute;
            bottom: -2px;
        }
        ::v-deep .input-span {
            border-bottom: 1px solid #000000;
            margin: 0 5px;
            position: relative;
            display: inline-block;
            min-width: 71px;
        }

        ::v-deep .span-answer {
            font-size: 0.933rem;
            border-bottom: 1px solid #000;
            min-width: 70px;
            height: 23px;
            display: inline-block;
            text-align: center;
            margin: 0 5px;
            color: #0590ff;
        }

        ::v-deep .error-answer {
            font-size: 0.933rem;
            border-bottom: 1px solid #000;
            min-width: 70px;
            height: 23px;
            display: inline-block;
            text-align: center;
            margin: 0 5px;
            color: #fd453d;
        }
    }
}
.num-text {
    font-weight: bold;
    font-size: 0.87rem;
    color: black;
    padding-right: 4px;
}
b {
    font-weight: bold !important;
}
</style>
